<template>
  <div class="llm-input-container">
    <div class="file-selector">
      <el-select v-model="selectedFile" placeholder="（可选）关联文件" clearable>
        <el-option v-for="file in fileList" :key="file.id" :label="file.name" :value="file.id"></el-option>
      </el-select>
    </div>
    <el-input
      v-model="command"
      type="textarea"
      :rows="4"
      placeholder="输入指令，例如：对基因数据做标准化->差异基因筛选->GO富集分析"
      resize="none"
    />
    <div class="input-actions">
      <el-button @click="clearCommand">清空</el-button>
      <el-button type="primary" @click="generateWorkflow" :loading="isLoading">
        {{ isLoading ? '生成中...' : '生成工作流' }}
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useWorkflowStore } from '../../stores/workflow';
import { useRouter } from 'vue-router';
import aiInteraction from '@/utils/ai-interaction';

const command = ref('');
const selectedFile = ref(null);
const fileList = ref([]); // 模拟文件列表
const isLoading = ref(false);
const workflowStore = useWorkflowStore();
const router = useRouter();

onMounted(() => {
  // 模拟获取已上传的文件列表
  fileList.value = [
    { id: 'file1', name: 'gene_expression.csv' },
    { id: 'file2', name: 'patient_metadata.tsv' },
  ];
});

const generateWorkflow = async () => {
  if (!command.value.trim()) {
    ElMessage.warning('指令不能为空');
    return;
  }
  isLoading.value = true;
  ElMessage.info('正在解析指令并生成工作流...');

  try {
    // 模拟上下文信息
    const context = {
      currentData: selectedFile.value ? fileList.value.find(f => f.id === selectedFile.value) : null,
      historyOperations: []
    };

    const workflow = await aiInteraction.translateUserQuery(command.value, context);
    
    if (workflow && workflow.nodes && workflow.nodes.length > 0) {
      const newWorkflowData = {
        nodeDataArray: workflow.nodes.map(node => ({
          key: node.id,
          text: node.name,
          type: node.type,
          loc: `${node.position.x} ${node.position.y}`,
          ...node.params && { ...node.params }
        })),
        linkDataArray: workflow.edges.map(edge => ({
          from: edge.from,
          to: edge.to
        }))
      };

      workflowStore.updateWorkflow(newWorkflowData);
      ElMessage.success('工作流生成成功！');
    } else {
      ElMessage.error('无法从指令中识别有效的操作');
    }
  } catch (error) {
    console.error('工作流生成出错:', error);
    ElMessage.error('工作流生成失败：' + error.message);
  }

  isLoading.value = false;
};

const clearCommand = () => {
  command.value = '';
};
</script>

<style scoped>
.llm-input-container {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.file-selector {
  width: 100%;
}

.input-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>